package no.nordicsemi.demo;

import no.nordicsemi.support.v18.scanner.ScanResult;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.bluetooth.ble.BleScanResult;

import java.util.ArrayList;
import java.util.List;

public class HistoryItemProvider extends BaseItemProvider {
    private List<ScanResult> list;
    private AbilitySlice slice;
    private int layout;

    public HistoryItemProvider(List<ScanResult> list, AbilitySlice slice, int layout) {
        this.list = list;
        this.slice = slice;
        this.layout = layout;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final Component comp;
        if (component == null) {
            comp = LayoutScatter.getInstance(slice).parse(layout, null, false);
        } else {
            comp = component;
        }
        if (list.size() > 0 && i < list.size() - 1) {
            ScanResult historyBean = list.get(i);
            BleScanResult bleScanResult = (BleScanResult) historyBean.getDevice();
            String str = bleScanResult.getPeripheralDevice().getDeviceName().toString();
            str = str.replace("Optional[", "");
            str = str.replace("]", "");
            Text text = (Text) comp.findComponentById(ResourceTable.Id_text);
            if (str.equals("Optional.empty")) {
                String strs = bleScanResult.getPeripheralDevice().getDeviceAddr().toString();
                text.setText(strs);
            } else {
                text.setText(str);
            }
        }
        return comp;
    }
}